/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.mail.service.processor;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.component.mail.domain.Mail;
import info.peigen.hotpot.component.mail.domain.MailTemplate;
import jakarta.activation.FileDataSource;
import org.noear.solon.annotation.Component;
import org.simplejavamail.api.email.EmailPopulatingBuilder;
import org.simplejavamail.email.EmailBuilder;

import java.util.Map;

/**
 * <b>(SendMimeMailProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/5/26
 */
@SuppressWarnings("rawtypes")
@Component
public class SendMimeMailProcessor extends AbstractMailServiceProcessor implements Processor {
    @SuppressWarnings("RedundantMethodOverride")
    @Override
    public Integer level() {
        return 50;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        Mail                   mail            = (Mail) serviceContext.getDomain();
        EmailPopulatingBuilder mimeMailBuilder = EmailBuilder.copying(email);
        mail.getTo().forEach(m -> mimeMailBuilder.to(m, m));

        if (ObjUtil.isNotNull(mail.getMailAttachments())) {
            mail.getMailAttachments()
                    .forEach(file -> mimeMailBuilder.withAttachment(file.getAttachmentName(), new FileDataSource(file.getAttachmentUrl())));
        }
        mailer.sendMail(mimeMailBuilder.buildEmail());
    }

    private void parseMailTemplate(EmailPopulatingBuilder mimeMailBuilder, MailTemplate mailTemplate, Mail mail) {
        mimeMailBuilder.withPlainText(mail.getContext());

        if (ObjUtil.isNotNull(mail.getMailTemplate())) {
            final String[]      context     = {mailTemplate.getContext()};
            Map<String, Object> templateMap = mailTemplate.getTemplateMap();
            templateMap.forEach((k, v) -> context[0] = StrUtil.replace(context[0], "@" + k, (String) v));
            mailTemplate.setContext(context[0]);
            mimeMailBuilder.withPlainText(mail.getMailTemplate().getContext());
        }
    }

}